import Layouts from '@/components/Layout';
import React, { useEffect, useState } from 'react';
import { Input, Typography, Radio, RadioChangeEvent, Pagination, Form, Spin, Empty } from 'antd';
import { TeamOutlined, BookOutlined } from '@ant-design/icons';
import './index.less';
import Tour from '@/components/Tour';
import bannerImg from '../../../public/images/CoNKtmOuuBxB4hvVACfrabfzL6c.jpg';
import { history, useLocation } from 'umi';
import { getTourList } from '@/service/api/touractivity';
import { TourList, TourSearch } from '@/types/touractivity';
import { getType } from '@/service/api/common';
import { CommonData } from '@/types/common';
const Tous: React.FC = () => {
  const location = useLocation();
  const [form] = Form.useForm();
  const [searchCname, setSearchCname] = useState<string>('');
  const [searchTourQuery, setSearchTourQuery] = useState<TourSearch>({
    pageNum: 1,
    pageSize: 9,
    city: location['query'].cname ?? null,
    tags: location['query'].tags ?? null,
    searchValue: location['query'].searchValue ?? null,
  });
  const [tourListData, setTourListData] = useState<TourList[]>([]);
  const [listTotal, setListTotal] = useState<number>(0);
  const [listLoading, setListLoading] = useState<boolean>(false);
  const [typeData, setTypeData] = useState<CommonData[]>([]);
  const [value, setValue] = useState<string | number>('');
  const [radioButtonValue, setRadioButtonValue] = useState<string>('全部');
  const handleChangePage = (page: number, pageSize: number) => {
    setSearchTourQuery({
      pageNum: page,
      pageSize,
      city: searchCname,
      searchValue: value,
      tags: radioButtonValue === '全部' ? '' : radioButtonValue,
    });
  };
  // 获取列表数据
  const getTourListData = async () => {
    try {
      setListLoading(true);
      // 如果说后端说city没值就别传这个键过来的话怎么办?
      // if (!location['query'].cname && !searchCname) {
      //   delete searchTourQuery.city;
      // } else {
      //   searchTourQuery.city = location['query'].cname || searchCname;
      // }
      console.log(value);

      if (value || location['query'].searchValue) {
        searchTourQuery.searchValue = value || location['query'].searchValue;
      } else {
        delete searchTourQuery.searchValue;
      }
      const { rows, total }: { rows: TourList[]; total: number } = await getTourList(
        searchTourQuery,
      );
      console.log(rows);
      setTourListData(rows);
      setListTotal(total);
    } finally {
      setListLoading(false);
    }
  };
  const onSearch = (value: string) => {
    searchResetQuery(value);
  };
  const handleSearchChange = (e: any) => {
    const { value } = e.target;
    if (value === '') {
      // 清空输入框
      searchResetQuery(value);
    }
  };
  const searchResetQuery = (value: string) => {
    setSearchCname(value);
    setSearchTourQuery((searchTourQuery) => ({ ...searchTourQuery, city: value }));
    const { cname, tags, searchValue } = location['query'];
    if (cname || tags || searchValue) {
      // 清空路由参数
      history.push('/tours');
    }
  };
  const onChange = (e: RadioChangeEvent) => {
    setValue(e.target.value);
    setSearchTourQuery({
      pageNum: searchTourQuery.pageNum,
      pageSize: searchTourQuery.pageSize,
      city: searchCname,
      searchValue: e.target.value,
      tags: radioButtonValue === '全部' ? '' : radioButtonValue,
    });
  };
  const handleChangeRadioButton = (e: RadioChangeEvent) => {
    setRadioButtonValue(e.target.value);
    setSearchTourQuery({
      pageNum: searchTourQuery.pageNum,
      pageSize: searchTourQuery.pageSize,
      city: searchCname,
      searchValue: value,
      tags: e.target.value === '全部' ? '' : e.target.value,
    });
  };
  const getTypeData = async () => {
    const { data }: { data: CommonData[] } = await getType({
      dictType: 'adv_tag',
    });
    setTypeData(data);
  };
  useEffect(() => {
    getTypeData();
    // const location = useLocation()
    // location.query // 类型“Location”上不存在属性“query”。
    // 实际上是有的 ，但是类型声明就没有，请问各位如何解决的 ^3.3.2
    // 官方暂时还没处理，改动比较大；我目前是用location['query']这种形式来暂时解决的
    const { cname, tags, searchValue } = location['query'];
    if (cname) {
      form.setFieldsValue({
        cname,
      });
      setSearchCname(cname);
    }
    if (tags) setRadioButtonValue(tags);
    console.log(searchValue);
    if (searchValue) setValue(Number(searchValue));
  }, []);
  useEffect(() => {
    getTourListData();
  }, [searchTourQuery]);
  const tl = () => {
    return (
      <div className="banner_wrapper">
        <img src={bannerImg} alt="" />
        <div className="banner_title">
          <p>你好, 世界!</p>
          <span className="sub_title">俄罗斯，曾以为你是冷漠的战斗民族，殊不知你如此浪漫温柔</span>
        </div>
        <div className="search_wrapper">
          <Form form={form}>
            <Form.Item name="cname">
              <Input.Search
                size="large"
                placeholder="我想去..."
                onSearch={onSearch}
                enterButton
                allowClear
                onChange={handleSearchChange}
              />
            </Form.Item>
          </Form>
        </div>
      </div>
    );
  };
  return (
    <Layouts tl={tl()}>
      <div className="filter_warpper">
        <div className="first_fliter filter_item">
          <div className="filter_type_tit">
            <Typography.Title level={5} style={{ margin: 0, fontWeight: 'normal' }}>
              <TeamOutlined style={{ marginRight: 8 }} />
              团队规模：
            </Typography.Title>
          </div>
          <Radio.Group onChange={onChange} value={value}>
            <Radio value="">不限</Radio>
            <Radio value={1}>1</Radio>
            <Radio value={2}>2</Radio>
            <Radio value={3}>3</Radio>
            <Radio value={4}>4</Radio>
            <Radio value={5}>5</Radio>
            <Radio value={6}>6</Radio>
            <Radio value={7}>7</Radio>
            <Radio value={8}>8</Radio>
            <Radio value={9}>9</Radio>
            <Radio value={10}>10</Radio>
          </Radio.Group>
        </div>
        <div className="first_fliter filter_item">
          <div className="filter_type_tit">
            <Typography.Title level={5} style={{ margin: 0, fontWeight: 'normal' }}>
              <BookOutlined style={{ marginRight: 8 }} />
              冒险类型：
            </Typography.Title>
          </div>
          <Radio.Group
            value={radioButtonValue}
            buttonStyle="solid"
            onChange={handleChangeRadioButton}
          >
            <Radio.Button key="全部" value="全部">
              全部
            </Radio.Button>
            {typeData.map((item) => (
              <Radio.Button key={item.dictCode} value={item.dictValue}>
                {item.dictValue}
              </Radio.Button>
            ))}
          </Radio.Group>
        </div>
      </div>
      <Spin tip="正在玩命加载..." size="large" spinning={listLoading}>
        <div className="tours_wrapper">
          {tourListData.map((item) => (
            <Tour
              key={item.id}
              title={item.title}
              id={item.id}
              time={item.time}
              price={item.price}
              remark={item.remark}
              userInfo={item.user}
              bacImg={item.bacImg}
              tags={item.tags}
            ></Tour>
          ))}
        </div>
      </Spin>
      <div className="pagination_wrapper">
        {listTotal !== 0 && (
          <Pagination
            current={searchTourQuery.pageNum}
            total={listTotal}
            showTitle
            pageSize={searchTourQuery.pageSize}
            showSizeChanger={false}
            onChange={handleChangePage}
          />
        )}
        {!listLoading && listTotal === 0 && <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />}
      </div>
    </Layouts>
  );
};
export default Tous;
